package com.xujl.mvcbind.ui.db.model;

import android.os.Bundle;

import com.xujl.fastlib.base.BaseModel;
import com.xujl.fastlib.base.IControl;
import com.xujl.fastlib.utils.DateUtil;
import com.xujl.fastlib.utils.NumberUtils;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.mvcbind.bean.AddOverTimeEntity;
import com.xujl.mvcbind.bean.OverTimeEntity;
import com.xujl.mvcbind.consts.BundleKey;
import com.xujl.mvcbind.db.DBManager;
import com.xujl.mvcbind.db.OverTimeHelper;
import com.xujl.mvcbind.exception.ParamsException;
import com.xujl.mvcbind.window.DatePickerBottomWindow;


/**
 * <pre>
 *     author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2019/08/20
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class AddOverTimeFragmentModel extends BaseModel implements DatePickerBottomWindow.CompleteListener {
    private AddOverTimeEntity mEntity = new AddOverTimeEntity();
    private OverTimeHelper mHelper;

    @Override
    public void init (IControl control) {
        mHelper = DBManager.getInstance().getOverTimeHelper();
    }

    public AddOverTimeEntity getEntity () {
        return mEntity;
    }

    public void saveData () throws ParamsException {
        if (StringUtils.isEmpty(mEntity.getDate())) {
            throw new ParamsException("请选择日期");
        }
        if (StringUtils.isEmpty(mEntity.getDuration())) {
            throw new ParamsException("请选择日期");
        }
        final OverTimeEntity entity = new OverTimeEntity();
        entity.setDate(DateUtil.getTime(mEntity.getDate(), DateUtil.Y_M_D_H_M));
        entity.setDuration(mEntity.getDuration());
        entity.setType(mEntity.getType() ? OverTimeEntity.TYPE_OVERTIME : OverTimeEntity.TYPE_LEAVE);
        entity.setRemark(mEntity.getRemark());
        entity.setId(mEntity.getId());
        if (mEntity.getId() == null) {
            mHelper.insert(entity);
        } else {
            mHelper.update(entity);
        }
    }

    public void durationAdd () {
        mEntity.setDuration((NumberUtils.doubleOf(mEntity.getDuration()) + 1) + "");
    }

    public void durationSub () {
        mEntity.setDuration((NumberUtils.doubleOf(mEntity.getDuration()) - 1) + "");
    }

    public void saveBundle (Bundle arguments) {
        if (arguments != null) {
            OverTimeEntity entity = (OverTimeEntity) arguments.getSerializable(BundleKey.DATA);
            if (entity != null) {
                mEntity.setId(entity.getId());
                mEntity.setDuration(entity.getDuration());
                mEntity.setType(entity.getType() == OverTimeEntity.TYPE_OVERTIME);
                mEntity.setDate(DateUtil.getDateToString(entity.getDate(), DateUtil.Y_M_D_H_M));
                mEntity.setRemark(entity.getRemark());
            }
        }
    }

    @Override
    public void onCompleteClick (String timeLong) {
        mEntity.setDate(DateUtil.getDateToString(timeLong, DateUtil.Y_M_D_H_M));
    }
}
